package org.com.ashen.service.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.codec.binary.Base64;

public class GZIPUtils  {
    public static final String GZIP_ENCODE_UTF_8 = "UTF-8"; 
    public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";
    public static final String GZIP_ENCODE_GB2312 = "GB2312";

    
    public static byte[] compress(String str, String encoding) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(encoding));
            gzip.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
    
    public static byte[] compress(String str) throws IOException {  
        return compress(str, GZIP_ENCODE_UTF_8);  
    }
    
    public static byte[] uncompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
    
    public static String uncompressToString(byte[] bytes, String encoding) {  
        if (bytes == null || bytes.length == 0) {  
            return null;  
        }  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);  
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);  
            byte[] buffer = new byte[256];  
            int n;  
            while ((n = ungzip.read(buffer)) >= 0) {  
                out.write(buffer, 0, n);  
            }  
            return out.toString(encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String uncompressToString(byte[] bytes) {  
        return uncompressToString(bytes, GZIP_ENCODE_UTF_8);  
    } 
    
    public static void main(String[] args) throws IOException {
        
//        System.out.println("字符串长度："+s.length());
//        System.out.println("压缩后：："+compress(s).length + new String(compress(s)));
//        System.out.println("解压后："+uncompress(compress(s)).length);
//        System.out.println("解压字符串后：："+uncompressToString(compress(s)));
    	
    	
    	  try {
//			unZip("C://Users//Administrator//Desktop//a.zip", "C://Users//Administrator//Desktop", false);
//			zip("C:/Users/Administrator/Desktop/a.zip", "C:/Users/Administrator/Desktop/a", false);
//			
//			String aa = file2String("C:/Users/Administrator/Desktop/a.zip");
//			System.out.println(aa);
//			System.out.println(aa.length());
    		  //8428
//			String aa = "UEsDBBQACAgIAA9+pU4AAAAAAAAAAAAAAAABAAAALwMAUEsHCAAAAAACAAAAAAAAAFBLAwQUAAgICAAPfqVOAAAAAAAAAAAAAAAABQAAAGEudHh0JYoxC4AgFAb/yzdH0fq2KOcgHFpLJAOT8D0xiP57UtvdcTeGTnegG1ECqK3AB4dtD1eKHgQncjI1Tc65dusl2dcm4L+Ww5ajEJ4Kapr6cVAl4BOtZv0LJ2MsM0hiss8LUEsHCNHjK/JgAAAAcQAAAFBLAQIUABQACAgIAA9+pU4AAAAAAgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAvUEsBAhQAFAAICAgAD36lTtHjK/JgAAAAcQAAAAUAAAAAAAAAAAAAAAAAMQAAAGEudHh0UEsFBgAAAAACAAIAYgAAAMQAAAAAAA==";
//			String aa = "UEsDBBQACAgIAA9+pU4AAAasdfBQAAAGEudHh0JYoxC4AgFAb/yzdH0fq2KOcgHFpLJAOT8D0xiP57UtvdcTeGTnegG1ECqK3AB4dtD1eKHgQncjI1Tc65dusl2dcm4L+Ww5ajEJ4Kapr6cVAl4BOtZv0LJ2MsM0hiss8LUEsHCNHjK/JgAAAAcQAAAFBLAQIUABQACAgIAA9+pU4AAAAAAgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAvUEsBAhQAFAAICAgAD36lTtHjK/JgAAAAcQAAAAUAAAAAAAAAAAAAAAAAMQAAAGEudHh0UEsFBgAAAAACAAIAYgAAAMQAAAAAAA==";
    		  String aa = file2String("C:\\Users\\Administrator\\Desktop\\a.txt");
    		  System.out.println(aa);
//					string2File(aa, "C:/Users/Administrator/Desktop/d.zip");
					string2File(aa, "D:/a.txt");
    	  } catch (Exception e) {
			e.printStackTrace();
		}
    	
    	
    	
//    	Base64 base64 = new Base64();
//    	 String aa = "UEsDBBQAAAAIAGZdqE53N4IjCwAAAAkAAAAGAAAAYWEudHh0S0lLPLV/y+ftnwBQSwECHwAUAAAACABmXahOdzeCIwsAAAAJAAAABgAkAAAAAAAAACAAAAAAAAAAYWEudHh0CgAgAAAAAAABABgA6z57KVAF1QHnsvuUHgPVAeey+5QeA9UBUEsFBgAAAAABAAEAWAAAAC8AAAAAAA==";
//    	 byte[] buffer = base64.decode(aa);
//    	  System.out.println("BASE64转译byte111:" + new String(buffer));
//    	 String bbString = new String(buffer,"utf-8");
//    	 byte[] buffer2=bbString.getBytes("utf-8");
//    	 
//         System.out.println("BASE64转译byte111:" + new String(buffer2));
    }
   
 
    public static void zip(String zipFileName, String filePath,boolean isDelete) throws Exception {

    	  zip(zipFileName, new File(filePath),isDelete);
    }

     public static void zip(String zipFileName, File inputFile,boolean isDelete) throws Exception {

	  ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
	  
	  if(!inputFile.exists()){
	   throw new FileNotFoundException("在指定路径未找到需要压缩的文件！");
	  }
	  
	  zip(out, inputFile, "",isDelete);// 递归压缩方法
	  System.out.println("Zip Done.");
	  out.close();
	 }
    private static void zip(ZipOutputStream out, File f, String base,boolean isDelete) throws Exception {

    	  if(f.isDirectory()) { // 如果是文件夹，则获取下面的所有文件
    	   File[] fl = f.listFiles();
    	   out.putNextEntry(new ZipEntry(base + "/"));
    	   base = base.length() == 0 ? "" : base + "/";
    	   for(int i = 0; i < fl.length; i++) {
    	    zip(out, fl[i], base + fl[i].getName(),isDelete);
    	   }
    	  } else { // 如果是文件，则压缩
    	   out.putNextEntry(new ZipEntry(base)); // 生成下一个压缩节点
    	   FileInputStream in = new FileInputStream(f); // 读取文件内容
    	   int b;
    	   while((b = in.read()) != -1){
    	    out.write(b); // 写入到压缩包
    	   }
    	   in.close();
    	  }
    	  if(isDelete){
    	   f.delete();
    	  }
    	}

    
    public static String fileToString(String filePath) throws IOException {
		File file = new File(filePath);
		FileInputStream is = new FileInputStream(file);
		String fileStr = streamToString(is);
		return fileStr;
	}
    public static String streamToString(InputStream inputStream) throws IOException {
		byte[] bt = toByteArray(inputStream);
		inputStream.close();
		String out = new String(bt, "utf-8");
		return out;
	}
    public static byte[] toByteArray(InputStream inputStream) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		byte[] result = null;
		try {
			int n = 0;
			while ((n = inputStream.read(buffer)) != -1) {
				out.write(buffer, 0, n);
			}
			result = out.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			out.close();
		}
		return result;
	}

    public static void string2File(String base64Code, String targetPath) {
        System.out.println("20个字符" + base64Code.substring(0, 50));
        System.out.println("BASE64转译String333:" + base64Code.length());
        byte[] buffer;
        FileOutputStream out = null;
        FileOutputStream out2 = null;
        try {
            Base64 base64 = new Base64();
            //解码
            buffer = base64.decode(base64Code);
            System.out.println("BASE64转译byte111:" + buffer.length);
            
            System.out.println(new String(buffer,"gb2312"));
            out = new FileOutputStream(targetPath);
            out.write(buffer);
//            out = new FileOutputStream(targetPath);
//            out.write(base64Code.getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out2 != null) {
                try {
                    out2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
        }
 
    }
    
    
    public static String file2String(String path) {
        File file = new File(path);
        FileInputStream fis = null;
        StringBuffer content = new StringBuffer();
        try {
            fis = new FileInputStream(file);
            int length = 2 * 1024 * 1024;
            byte[] byteAttr = new byte[length];
            int byteLength = -1;
 
            while ((byteLength = fis.read(byteAttr, 0, byteAttr.length)) != -1) {
 
                String encode = "";
                if (byteLength != byteAttr.length) {
                    byte[] temp = new byte[byteLength];
                    System.arraycopy(byteAttr, 0, temp, 0, byteLength);
                    //使用BASE64转译
                    Base64 base64 = new Base64();
                    encode = base64.encodeToString(temp);
                    content.append(encode);
//                    content.append(new String(temp, "utf-8"));
                } else {
                    Base64 base64 = new Base64();
                    encode = base64.encodeToString(byteAttr);
                    content.append(encode);
//                    content.append(new String(byteAttr, "utf-8"));
                }
            }
 
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return content.toString();
    }
    
    
    public static void writeFile(String str, String filename) {

    		File file=new File(filename);
             if(!file.exists()){  
                 try {
                	 File fileParent = file.getParentFile();  
                	 if(!fileParent.exists()){  
                	     fileParent.mkdirs();  
                	 } 
                	 file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}  
            } 
        FileWriter writer;
        try {
            writer = new FileWriter(filename);
            writer.write("");//清空原文件内容
            writer.write(str);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}